//
//  addAddressVC.m
//  BeautyPicture
//
//  Created by 沈振邦 on 15/8/12.
//  Copyright (c) 2015年 szb. All rights reserved.
//

#import "addAddressVC.h"
#import "HZAreaPickerView.h"
#import "editAddressView.h"
#import "AccountTool.h"
#import "BPLoginViewController.h"
#import "AccountTool.h"
#import "MBProgressHUD+MJ.h"

#define BgColor  BPColor(239, 239, 239)

@interface addAddressVC ()<UITextFieldDelegate,HZAreaPickerDelegate,UIScrollViewDelegate>

@property (nonatomic ,strong)editAddressView *nameFiled;

@property (nonatomic ,strong)editAddressView *phoneFiled;

@property (nonatomic,strong)editAddressView *addressFiled;

@property (nonatomic,strong)editAddressView *detailAddress;

@property (nonatomic ,strong)editAddressView *timeFiled;

@property (nonatomic,strong)HZAreaPickerView *locatePicker;

@end

@implementation addAddressVC


- (void)viewWillAppear:(BOOL)animated{
    
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
//    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithButtonName:@"返回" tatget:self action:@selector(back)];
//    self.title = @"地址";
    
    _backView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:_backView];
    _backView.delegate = self;
    _backView.backgroundColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(changeInfo)];
    [self setUpTextFiled];
    addressManger = [[CoreDateManager alloc] init];
    
    [self createButton];
}

// 创建 返回按钮
- (void)createButton{
    
//    UIButton *buttonBig = [[UIButton alloc] initWithFrame:CGRectMake(20, 25, 50, 50)];
//    buttonBig.backgroundColor = [UIColor yellowColor];
//    [self.view addSubview:buttonBig];
    
    UIButton *buttonBig = [[UIButton alloc] initWithFrame:CGRectMake(20, 25, 80, 50)];
    buttonBig.backgroundColor = [UIColor clearColor];
    [buttonBig addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonBig];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 23, 23)];
    [button setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    [buttonBig addSubview:button];
    
//    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(20, 25, 23, 23)];
//    [button setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
//    [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:button];
    
    UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 30, 20, 100, 30)];
    name.text = @"新增地址";
    name.textColor = BPFenHongColor;
    name.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:name];
    
    UIImageView *im = [[UIImageView alloc] initWithFrame:CGRectMake(0, 60, self.view.frame.size.width, 5)];
    im.image = [UIImage imageNamed:@"波纹线"];
    [self.view addSubview:im];
    
    
    UIButton *buttonSave = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 55, 25, 60, 40)];
    buttonSave.backgroundColor = [UIColor clearColor];
    [buttonSave addTarget:self action:@selector(changeInfo) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonSave];
    
    UIButton *buttonHome = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
    [buttonHome setTitle:@"保存" forState:UIControlStateNormal];
    [buttonHome setTitleColor:BPFenHongColor forState:UIControlStateNormal];
    buttonHome.titleLabel.font = [UIFont systemFontOfSize:17];
    [buttonHome addTarget:self action:@selector(changeInfo) forControlEvents:UIControlEventTouchUpInside];
    [buttonSave addSubview:buttonHome];
    
}
// 头部的 两个按钮
- (void)button:(UIButton *)b{
    [self.navigationController popViewControllerAnimated:YES];
}




- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)setUpTextFiled
{
    CGFloat viewH = 40.0f;
    _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 60, BPScreenW, viewH * 6.0)];
    _bgView.backgroundColor = [UIColor whiteColor];
    [_backView addSubview:_bgView];
    
    _nameFiled = [[editAddressView alloc] initWithFrame:CGRectMake(BPStatusCellInset, 0, BPScreenW - BPStatusCellInset, viewH)];
    [self setUpEditView:_nameFiled withPlaceholder:@"名字" addLabelName:@"收货人"];
    
    _phoneFiled = [[editAddressView alloc] initWithFrame:CGRectMake(BPStatusCellInset, viewH, BPScreenW - BPStatusCellInset, viewH)];
    [self setUpEditView:_phoneFiled withPlaceholder:@"11位手机号" addLabelName:@"手机号码"];
    
    
    _addressFiled = [[editAddressView alloc] initWithFrame:CGRectMake(BPStatusCellInset, viewH * 2.0, BPScreenW - BPStatusCellInset, viewH)];
    [self setUpEditView:_addressFiled withPlaceholder:@"选择地区" addLabelName:@"地区信息"];
    UIButton *areaBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    areaBtn.frame = _addressFiled.bounds;
    [_addressFiled addSubview:areaBtn];
    [areaBtn addTarget:self action:@selector(changeArea) forControlEvents:UIControlEventTouchUpInside];
    
    _detailAddress = [[editAddressView alloc] initWithFrame:CGRectMake(BPStatusCellInset, viewH * 3.0, BPScreenW - BPStatusCellInset, viewH * 2.0)];
    [self setUpEditView:_detailAddress withPlaceholder:@"街道门牌信息" addLabelName:@"详细地址"];
    
    _backView.contentSize = CGSizeMake(BPScreenW, BPScreenH);
    //_timeFiled = [[editAddressView alloc] initWithFrame:CGRectMake(BPStatusCellInset, viewH * 5.0, BPScreenW - BPStatusCellInset, viewH)];
    //[self setUpEditView:_timeFiled withPlaceholder:@"周一到周五" addLabelName:@"收货时间"];
    
    [self inputAddressData:self.addressModel];
}

- (void)setUpEditView:(editAddressView *)editView withPlaceholder:(NSString *)holder addLabelName:(NSString *)name
{
    editView.rightText.delegate = self;
    editView.rightText.placeholder = holder;
    editView.leftLabel.text = name;
    [_bgView addSubview:editView];
}

- (void)changeArea
{
    [self.view endEditing:YES];
    if (self.locatePicker == nil) {
        self.locatePicker = [[HZAreaPickerView alloc] initWithStyle:HZAreaPickerWithStateAndCityAndDistrict delegate:self];
        [self.locatePicker showInView:self.view];
    }
}

//选择地址
- (void)pickerDidChaneStatus:(HZAreaPickerView *)picker
{
    _addressFiled.rightText.text = [NSString stringWithFormat:@"%@ %@ %@", picker.locate.state, picker.locate.city,picker.locate.district];
    [self cancelLocatePicker];
}
//取消选择地址
- (void)cancelAreaChoose:(HZAreaPickerView *)picker
{
    [self cancelLocatePicker];
}

-(void)cancelLocatePicker
{
    [self.locatePicker cancelPicker];
    self.locatePicker.delegate = nil;
    self.locatePicker = nil;
}
//传入信息
- (void)inputAddressData:(BPAddressModel *)model
{
    _nameFiled.rightText.text = model.realname;
    if ([AccountTool account].uid != nil) {
        NSLog(@"+++++++%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"userPhone"]);
        _phoneFiled.rightText.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"userPhone"];
    }else{
        
        _phoneFiled.rightText.text = model.phone;
    }
    if (model.province != nil) {
        _addressFiled.rightText.text = [NSString stringWithFormat:@"%@ %@ %@",model.province,model.city,model.area];
    }
    _detailAddress.rightText.text = model.address;
   // _timeFiled.rightText.text = model.time;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [textField setReturnKeyType:UIReturnKeyDone];
    //CGRect frame = textField.frame;
    //int offsetY = frame.origin.y + frame.size.height - (self.view.frame.size.height - 320.0f);
    if (textField == _detailAddress.rightText) {
        [UIView animateWithDuration:0.3f animations:^{
            self.view.frame = CGRectMake(0, -50, self.view.frame.size.width, self.view.frame.size.height);
        }];

    }
//    CGRect frame = textField.frame;
//    int offsetY = frame.origin.y + frame.size.height - (self.view.frame.size.height - 320.0f);
//    if (offsetY > 0) {
//        [UIView animateWithDuration:0.3f animations:^{
//            self.view.frame = CGRectMake(0, -offsetY, self.view.frame.size.width, self.view.frame.size.height);
//        }];
//    }
//    [UIView commitAnimations];
}
//
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == _detailAddress.rightText) {
        [UIView animateWithDuration:0.3 animations:^{
            self.view.frame =  CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}

//信息更改
- (void)changeInfo
{
    if ([self isStrEmpty:_addressFiled.rightText.text] == NO) {
        if (_addressModel == nil) {
            _addressModel = [[BPAddressModel alloc] init];
        }
        _addressModel.realname = _nameFiled.rightText.text;
        if ([self checkPhoneNumber] == YES) {
            
//            if ([AccountTool account].uid != nil) {
//                NSLog(@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"userPhone"]);
//                _phoneFiled.rightText.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"userPhone"];
//            }else{
            
                _addressModel.phone = _phoneFiled.rightText.text;
//            }

            NSArray *arry = [_addressFiled.rightText.text componentsSeparatedByString:@" "];
            for (int i = 0; i < arry.count; i++) {
                if (i == 0) {
                    _addressModel.province = arry[0];
                }else if(i == 1){
                    _addressModel.city = arry[1];
                }else{
                    _addressModel.area = arry[2];
                }
            }
            _addressModel.address = _detailAddress.rightText.text;
            _addressModel.time = _timeFiled.rightText.text;
            _addressModel.status = 1;
            
        
        
        if ([AccountTool account].uid != nil) {
            _addressModel.uid = [AccountTool account].uid;
        }
        [AccountTool addOrChangeOrdeleteAddress:_addressModel success:^(paramAddress *result) {
            if ([result.info isKindOfClass:[NSNull class]]) {
                //表明没有更改，或者改了时间，所以无需操作
            }else if ([result.info intValue] == 1) {
                //更新收货地址
                [addressManger updateAddressWithAddress:_addressModel];
            }else{
                _addressModel.addressid = [result.info intValue];
                //插入了收货地址
                [addressManger insertOneAddress:_addressModel];
            }
            
            [MBProgressHUD showSuccess:@"保存地址成功"];
            _block(_addressModel);
            [self.navigationController popViewControllerAnimated:YES];
            
        } failure:^(NSError *error) {
            [MBProgressHUD showError:@"网络错误"];
            [self.navigationController popViewControllerAnimated:YES];
        }];
        
        }
    }else{
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"地址不能空" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
        [alert show];
    }
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    //[self.view endEditing:YES];
    [self cancelLocatePicker];
}

//判断text是否为空
-(BOOL)isStrEmpty:(NSString*)str
{
    if (str == nil || str == NULL)
    {
        return YES;
    }
    if ([str isKindOfClass:[NSNull class]])
    {
        return YES;
    }
    if ([str length] <= 0)
    {
        return YES;
    }
    return NO;
}

- (BOOL)checkPhoneNumber
{
    
    
    NSString *phoneNumber = @"^((13[0-9])|(147)|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneNumber];
    
    
    BOOL isMatch = [pred evaluateWithObject:_phoneFiled.rightText.text];
    
    if (!isMatch) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入正确的11位手机号码" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return NO;
    }else
    {
        return YES;
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
